const { getUploadedUrl } = require('../../utils/upload');
const { getBannerList, addBanner, updateBanner, removeBanner } = require('../../model/banner');
/**
 * 获取轮播图列表
*/
const bannerList = async (req, res) => {
    const output = { code: 200, msg: '操作成功' }
    var { bus_id } = req.query;
    if (!bus_id) bus_id = 0;
    const result = await getBannerList({ bus_id, status: 1 });
    if (!result) {
        output.code = 500;
        output.msg = "操作失败";
        return res.send(output);
    }
    output.data = result;
    res.send(output);
}

/**
 * 新增轮播图
 * 
*/
const bannerAdd = async (req, res) => {
    const output = { code: 200, msg: '操作成功' }
    const payload = { ...req.body }
    if (Object.keys(payload).length === 0) {
        output.code = 500
        output.msg = '参数错误'
        return res.send(output)
    }
    const { file } = req;
    // 获取上传完成的图片地址
    if (file) payload.img = getUploadedUrl(file);
    const result = await addBanner(payload)
    if (result) output.data = result
    res.send(output);
}



/**
 * 更新轮播图
*/
const bannerUpdate = async (req, res) => {
    const output = { code: 200, msg: '操作成功' }
    const payload = { ...req.body }
    if (Object.keys(payload).length === 0) {
        output.code = 500
        output.msg = '参数错误'
        return res.send(output)
    }
    const { file } = req;
    // 获取上传完成的图片地址
    if (file) payload.img = getUploadedUrl(file);
    const result = await updateBanner(payload)
    if (result) output.data = result
    res.send(output);
}

/**
 * 删除轮播图 
 * 
 */
const bannerRemove = async (req, res) => {
    const output = { code: 200, msg: '操作成功' }
    const { id } = req.query
    if (!id) {
        output.code = 500;
        output.msg = '参数错误:缺少参数id'
        return res.send(output)
    }
    const result = await removeBanner(id)
    output.data = result
    res.send(output)
}

module.exports = {
    bannerList, bannerAdd, bannerUpdate, bannerRemove
}